package util

import (
	"encoding/json"
	"io/ioutil"
	"net/http"
	"os"
	"time"
)

var App_secret = ""

type AccessToken struct {
	Access_token string
	Expires_in int
	Errcode int
	errmsg string
}

func GetAccessToken() {
	query := "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+os.Getenv("APP_ID")+"&secret="+os.Getenv("APP_SECRET")
	apps := &AccessToken{}
	if resp, err := http.Get(query); err == nil  {
		defer resp.Body.Close()
		if body, err := ioutil.ReadAll(resp.Body); err == nil {
			if err = json.Unmarshal(body, &apps); err==nil {
				App_secret = apps.Access_token
			}
		}
	} else {
		time.Sleep(3 * time.Second)
		GetAccessToken()
	}
}

func AccessTokenServlet() {
	GetAccessToken()
	//新建计时器，7秒以后触发，go触发计时器的方法比较特别，就是在计时器的channel中发送值
	ticker :=time.NewTicker( 6900 * time.Second)
	for _ = range ticker.C {
		GetAccessToken() //执行我们想要的操作
	}
}